<template>
  <div>
    <div class="pageTitleWhole">
      <a-breadcrumb>
        <a-breadcrumb-item>加油卡总账户</a-breadcrumb-item>
      </a-breadcrumb>
    </div>
    <div class="pageContentWhole">
      <a-row :gutter="[48]">
        <a-col :span="8">
          <div id="liquidFill" style="width:100%;height:150px;"></div>
        </a-col>
        <a-col :span="8">
          <div class="ant-card-body1">
            <div>
              <p class="caiGou">采购入库（元）</p>
              <h1 class="cgYoul">{{truckOilInfo.inAmount}}</h1>
            </div>
            <p class="cgSale">
              &nbsp;
            </p>
          </div>
        </a-col>
        <a-col :span="8">
          <div class="ant-card-body1">
            <div>
              <p class="caiGou">充值出库（元）</p>
              <h1 class="cgYoul">{{truckOilInfo.outAmount}}</h1>
            </div>
            <p class="cgSale">
              &nbsp;
            </p>
          </div>
        </a-col>
      </a-row>
      <a-form layout="inline" ref="form" :style="'margin-top:60px;'">
          <a-form-item v-if="searchTable1Show" label="结算对象">
            <a-select class="selectInputWidth"
              show-search
              :show-arrow="false"
              :filter-option="false" :default-active-first-option="false"
              :not-found-content="null"
              v-model="searchForm1.custId"
              @search="handleNameChange"
            >
              <a-select-option key="">全部</a-select-option>
              <a-select-option v-for="d in nameLikeData" :key="d.id">{{ d.name }}</a-select-option>
            </a-select>
          </a-form-item>
          <a-form-item v-if="searchTable1Show" label="发票状态">
            <a-select v-model="searchForm1.isSettle" class="selectWidth">
              <a-select-option key="">全部</a-select-option>
              <a-select-option :key="0">未结清</a-select-option>
              <a-select-option :key="1">已结清</a-select-option>
            </a-select>
          </a-form-item>

          <a-form-item v-if="!searchTable1Show" label="车辆">
            <a-select class="selectInputWidth"
              show-search
              :show-arrow="false"
              :filter-option="false" :default-active-first-option="false"
              :not-found-content="null"
              v-model="searchForm2.truckId"
              @search="handleCarNameChange"
            >
              <a-select-option key="">全部</a-select-option>
              <a-select-option v-for="d in carLikeData" :key="d.truckId">{{ d.truckNumber }}</a-select-option>
            </a-select>
          </a-form-item>
          <a-form-item v-if="!searchTable1Show" label="加油卡">
            <a-select class="selectInputWidth"
              show-search
              :show-arrow="false"
              :filter-option="false" :default-active-first-option="false"
              :not-found-content="null"
              v-model="searchForm2.cardId"
              @search="handleOilCardChange"
            >
              <a-select-option key="">全部</a-select-option>
              <a-select-option v-for="d in oilCardLikeData" :key="d.cardId">{{ d.cardNo }}</a-select-option>
            </a-select>
          </a-form-item>

          <a-form-item label="日期">
            <a-range-picker :value="searchDateRange" @change="onChangeDate" />
          </a-form-item>

          <a-form-item>
            <a-button type="primary" @click="handleSubmit1">查询</a-button>
          </a-form-item>
          <a-form-item>
            <a-button type="primary" @click="createRecord">+ 添加记录</a-button>
          </a-form-item>
          <a-form-item>
            <a-button type="primary" @click="exportExcel">导出Excel</a-button>
          </a-form-item>
      </a-form>
      <a-tabs
        @change="tabChange"
        :tab-bar-style="{margin:'20px 0 0 0'}"
      >
        <a-tab-pane :key="1" tab="采购入库" style="padding:0">
        </a-tab-pane>
        <a-tab-pane :key="2" tab="充值出库" style="padding:0">
        </a-tab-pane>
      </a-tabs>
      <a-row>
        <a-col :span="24">
          <a-table
            :columns="column"
            :loading="loading"
            :data-source="tableData"
            :pagination="pagination"
            row-key="batchNo"
          >
            <template slot="invoiceNo" slot-scope="text, record">
              <a v-if="record.invoiceNo" style="margin-right:10px" @click="viewInvoice(record.purchaseId)">{{record.invoiceNo}}</a>
              <a v-else @click="createInvoice(record.purchaseId)">添加发票</a>
            </template>
          </a-table>
        </a-col>
      </a-row>
    </div>

    <!-- 新增记录modal -->
    <a-modal :visible="visible" title="新增记录"
      :body-style="{padding:'24px 40px 0px 20px'}"
      width="640px"
      centered
      :destroyOnClose='true'
      :confirmLoading="confirmLoading"
      @ok="handleAdd"
      @cancel="handleCancel"
    >
      <a-row>
        <a-col :span="23" offset="1">
          <a-form-model
            ref="rulesForm"
            :model="formx"
            :rules="formRules"
            :label-col="{span:8}"
            :wrapper-col="{span:16}"
          >
            <a-col :span="20">
              <a-form-model-item label="记录类型">
                <a-radio-group v-model="businessType" @change="handleChangeBusinessType">
                  <a-radio :value="1">采购入库</a-radio>
                  <a-radio :value="2">加油出库</a-radio>
                </a-radio-group>
              </a-form-model-item>
            </a-col>

            <a-col :span="20">
              <template v-if="isbusinessType1">
                <a-form-model-item label="交易金额(元)" prop="amount">
                  <a-input-number v-model="form.amount" :min='0' :precision="2" :max="999999999999.99" style="width:100%"/>
                </a-form-model-item>
                <a-form-model-item label="结算对象" prop="custId">
                  <a-select style="width:100%"
                    show-search
                    :show-arrow="false"
                    :filter-option="false" :default-active-first-option="false"
                    :not-found-content="null"
                    v-model="form.custId"
                    @search="handleNameChangeModal"
                    @select="emptyChange"
                  >
                    <a-select-option v-for="d in nameLikeDataModal" :key="d.id">{{ d.name }}</a-select-option>
                  </a-select>
                </a-form-model-item>
              </template>
              <template v-if="!isbusinessType1">
                <a-form-model-item label="加油卡卡号" prop="cardId">
                  <a-select
                    show-search
                    :show-arrow="false"
                    :filter-option="false" :default-active-first-option="false"
                    :not-found-content="null"
                    v-model="m"
                    @search="handleOilCardChangeModal"
                    @select="handleOilCardSelect"
                  >
                    <a-select-option v-for="(d) in oilCardLikeDataModal" :key="d.cardId">{{ d.cardNo }}</a-select-option>
                  </a-select>
                </a-form-model-item>
                <a-col :span="24">
                  <a-col :span="8"><p class="descData">所属公司：</p></a-col>
                  <a-col :span="16">{{key1}}</a-col>
                </a-col>
                <a-col :span="24">
                  <a-col :span="8"><p class="descData">车辆：</p></a-col>
                  <a-col :span="16">{{key2}}</a-col>
                </a-col>
                <a-form-model-item label="交易金额(元)" prop="amount">
                  <a-input-number v-model="form2.amount" :min='0' :precision="2" :max="999999999999.99" style="width:100%"/>
                </a-form-model-item>
              </template>
            </a-col>
          </a-form-model>
        </a-col>
      </a-row>
    </a-modal>

    <a-modal :visible="visibleInvoice" title="发票详情"
      :bodyStyle="{minHeight: '400px'}"
      centered
      width="720px"
      :footer="null"
      @cancel="handleCancelPurchase"
    >
      <purchase-detail :id="purchaseId" :type="3"/>
    </a-modal>
  </div>
</template>

<script>
// eslint-disable-next-line no-unused-vars
import echartsLiquidfill from 'echarts-liquidfill'
import moment from 'moment'
import debounce from 'lodash/debounce'
import upload from '@/components/UpLoad'
import {commonExport} from '@/api/request'
import { queryCustNameList, queryTruckNumberDown, queryTruckOilCardDown } from '@/api'
import { queryOilCardPurchaseDetail, queryOilCardPurchaseList, addOilCardPurchase, rechargeTruckOilCard } from '@/api/landCenter'
import purchaseDetail from './purchaseDetailOfAccountAndEtc'

let queryColumn = null

const searchForm = (i) => {
  if (i === 1) {
    return {
      custId: '', // 结算对象
      isSettle: ''// 发票状态是否结清：1是，0否
    }
  } else if (i === 2) {
    return {
      truckId: '', // 车牌
      cardId: ''// 司机
    }
  }
}

const searchDate = {
  time1: '', // 开始时间
  time2: '' // 结束时间
}
const fomrMessage = `必填项不能为空`

export default {
  data () {
    const column1 = [
      {
        title: '采购批次',
        dataIndex: 'batchNo'
      },
      {
        title: '交易金额(元）',
        dataIndex: 'amount'
      },
      {
        title: '结算对象',
        dataIndex: 'custName'
      },
      {
        title: '日期',
        dataIndex: 'createTime',
        width: '120px'
      },
      {
        title: '发票状态',
        dataIndex: 'isSettle',
        width: '120px',
        customRender: (text, record, index) => {
          if (text === 1) {
            return <a-badge status="success" text="已结清"/>
          } else if (text === 0) {
            return <a-badge status="error" text="未结清"/>
          }
        },
        _needName: true
      },
      {
        title: '发票号',
        dataIndex: 'invoiceNo',
        scopedSlots: { customRender: 'invoiceNo' },
        fixed: 'right',
        width: 120
      }
    ]

    const column2 = [
      {
        title: '充值批次',
        dataIndex: 'batchNo'
      },
      {
        title: '加油卡',
        dataIndex: 'cardNo'
      },
      {
        title: '所属公司',
        dataIndex: 'custName'
      },
      {
        title: '车辆',
        dataIndex: 'truckNumber'
      },
      {
        title: '交易金额（元）',
        dataIndex: 'amount'
      },
      {
        title: '余额（元）',
        dataIndex: 'accountAmount'
      },
      {
        title: '日期',
        dataIndex: 'createTime',
        width: '180px'
      }
    ]

    queryColumn = [column1, column2]

    this.handleNameChange = debounce(this.handleNameChange, 800)
    this.handleNameChangeModal = debounce(this.handleNameChangeModal, 800)
    this.handleCarNameChange = debounce(this.handleCarNameChange, 800)
    this.handleOilCardChange = debounce(this.handleOilCardChange, 800)
    this.handleOilCardChangeModal = debounce(this.handleOilCardChangeModal, 800)

    return {
      m: '',
      labelCol: { span: 5 },
      wrapperCol: { span: 19 },
      truckOilInfo: {
        amount: '', // 当前余额
        inAmount: '', // 采购入库
        outAmount: '' // 充值出库
      },
      column: queryColumn[0],
      searchForm1: searchForm(1),
      searchForm2: searchForm(2),
      oilCardLikeData: [],
      oilCardLikeDataModal: [],
      nameLikeData: [],
      nameLikeDataModal: [],
      carLikeData: [],
      searchDate,
      searchDateRange: null,
      loading: false,
      tableData: [],
      pagination: {},
      pageNum: 1,
      pageSize: 10,
      tabIndex: 1, // 当前tab
      visible: false,
      businessType: 1,
      form: this.createForm1(),
      form2: this.createForm2(),
      formRules: {
        amount: [{required: true, message: fomrMessage, trigger: 'blur'}],
        custId: [{required: true, message: fomrMessage, trigger: ['blur', 'change']}],
        cardId: [{required: true, message: fomrMessage, trigger: ['blur', 'change']}]
      },
      key1: '',
      key2: '',
      truckNumberAndDriverData: [],
      visibleDetail: false,
      inAndOutId: null,
      // 发票详情
      visibleInvoice: false,
      purchaseId: null,
      confirmLoading: false
    }
  },
  components: {
    'ud-upload': upload,
    [purchaseDetail.name]: purchaseDetail
  },
  created () {

  },
  computed: {
    searchTable1Show () {
      return this.tabIndex === 1
    },
    isbusinessType1 () {
      return this.businessType === 1
    },
    formx () {
      return this.businessType === 1 ? this.form : this.form2
    }
  },
  methods: {
    createForm1 () {
      this.nameLikeDataModal = []
      return {
        amount: '', // 总单价(元/吨)
        custId: '' // 结算对象id（售油方）
      }
    },
    createForm2 () {
      this.key1 = ''
      this.key2 = ''
      return {
        cardId: '',
        amount: '',
        truckId: ''
      }
    },
    tabChange (i) {
      this.tabIndex = i
      this.businessType = i
      this[`searchForm${i}`] = searchForm(i)
      this.searchDateRange = null
      this.handleSubmit1()
    },
    onChangeDate (date, dateStr) {
      this.searchDate.time1 = dateStr[0]
      this.searchDate.time2 = dateStr[1]
      if (this.searchDate.time1) {
        this.searchDateRange = [moment(dateStr[0]), moment(dateStr[1])]
      } else {
        this.searchDateRange = null
      }
    },
    handleSubmit1 () {
      this.pageNum = 1
      this.handleSubmit()
    },
    handleSubmit () {
      let i = this.tabIndex
      this.column = queryColumn[i - 1]
      this.loading = true
      queryOilCardPurchaseList({
        ...this[`searchForm${i}`],
        ...this.searchDate,
        type: i, // 1、采购入库 2、充值出库
        pageNum: this.pageNum,
        pageSize: this.pageSize
      }).then(rsp => {
        this.loading = false
        this.tableData = rsp.data.list
        this.pagination = {
          current: this.pageNum,
          pageSize: rsp.data.pageSize,
          total: rsp.data.total,
          showQuickJumper: false,
          showSizeChanger: true,
          showTotal: total => `共${total}条记录 第${this.pageNum}/${rsp.data.pages}页`,
          onChange: pageNum => {
            this.pageNum = pageNum
            this.handleSubmit()
          },
          onShowSizeChange: (current, size) => {
            this.pageNum = current
            this.pageSize = size
            this.handleSubmit()
          }
        }
      })

      // 上方数据根据日期筛选
      queryOilCardPurchaseDetail(this.searchDate).then(rsp => {
        this.truckOilInfo = rsp.data
        this.liquidFill(this.truckOilInfo.amount)
      })
    },
    liquidFill (res) {
      let liquid = this.$echarts.init(
        document.getElementById('liquidFill')
      )
      let result
      if (res > 0) {
        result = 0.5
      } else {
        result = 0.2
      }
      liquid.setOption({
        series: [
          {
            type: 'liquidFill',
            data: [result],
            radius: '95%',
            backgroundStyle: {
              color: '#fff',
              shadowColor: '#fff',
              shadowBlur: 0
            },
            itemStyle: {
              normal: {
                shadowBlur: 0
              }
            },
            outline: {
              show: true, // 是否显示轮廓 布尔值
              borderDistance: 5, // 外部轮廓与图表的距离 数字
              itemStyle: {
                borderColor: result === 0.5 ? '#1890FF' : '#f5222d', // 边框的颜色
                borderWidth: 2 // 边框的宽度
              }
            },
            color: result === 0.5 ? ['#1890FF'] : ['#f5222d'],
            label: {
              position: ['50%', '50%'],
              formatter: function (param) {
                return `当前余额（元）\n${res}`
              },
              fontSize: 14,
              color: '#666'
            }
          }
        ]
      })
    },
    exportExcel () {
      let i = this.tabIndex
      commonExport('/truckStock/exportOilCardPurchaseList', {
        ...this[`searchForm${i}`],
        ...this.searchDate,
        type: i,
        pageNum: this.pageNum,
        pageSize: this.pageSize,
        columns: queryColumn[i - 1]
      })
    },
    createRecord (id) {
      if (!this.$root._bc.createRecord) {
        this.$message.error('您无此权限！')
        return
      }
      this.handleNameChangeModal() // 初始化采购结算对象
      this.handleOilCardChangeModal() // 初始化加油卡
      this.form = this.createForm1()
      this.form2 = this.createForm2()
      this.m = ''
      if (this.$refs.rulesForm) this.$refs.rulesForm.resetFields()
      this.businessType = this.tabIndex
      this.visible = true
    },
    handleOilCardSelect (cardId) {
      const t = this.oilCardLikeDataModal.filter(v => v.cardId === cardId)[0]
      if (t) {
        this.form2.cardId = t.cardId
        this.form2.truckId = t.truckId
        this.key1 = t.custName
        this.key2 = t.truckNumber
      }
      this.handleOilCardChangeModal()
    },
    handleAdd () {
      this.$refs.rulesForm.validate(valid => {
        if (valid) {
          this.confirmLoading = true
          if (this.isbusinessType1) {
            addOilCardPurchase({...this.form, type: 1}).then(rsp => {
              this.$message.success('新增成功')
              this.handleCancel()
              this.handleSubmit()
              setTimeout(() => { this.confirmLoading = false }, 1000)
            }).catch(() => { this.confirmLoading = false })
          } else {
            rechargeTruckOilCard(this.form2).then(rsp => {
              this.$message.success('新增成功')
              this.handleCancel()
              this.handleSubmit()
              setTimeout(() => { this.confirmLoading = false }, 1000)
            }).catch(() => { this.confirmLoading = false })
          }
        }
      })
    },
    handleCancel () {
      this.visible = false
    },
    handleChangeBusinessType () {
      this.form = this.createForm1()
      this.form2 = this.createForm2()
      this.$refs.rulesForm.resetFields()
    },
    handleNameChange (nameLike) { // 从应收结算对象当中选
      if (nameLike) {
        queryCustNameList({
          nameLike,
          belongCompany: 'JIA_TE',
          custTypeLike: 'SUPPLIER',
          status: 1,
          isReceivable: 1
        }).then(rsp => {
          this.nameLikeData = rsp.data
        })
      } else {
        this.nameLikeData = []
      }
    },
    handleNameChangeModal (nameLike = '') { // 应付供应商当中选择结算对象的名称
      queryCustNameList({
        nameLike,
        belongCompany: 'JIA_TE',
        custTypeLike: 'SUPPLIER',
        status: 1,
        isPayable: 1
      }).then(rsp => {
        this.nameLikeDataModal = rsp.data
      })
    },
    emptyChange (e) {
      this.handleNameChangeModal()
    },
    handleCarNameChange (nameLike) { // 正常状态的自营状态的所有牵引车
      if (nameLike) {
        queryTruckNumberDown({
          truckNumber: nameLike,
          isSelfOperation: 1,
          tractorOrTrailer: 1,
          status: 1
        }).then(rsp => {
          this.carLikeData = rsp.data
        })
      } else {
        this.carLikeData = []
      }
    },
    handleOilCardChange (nameLike) { // 加油卡
      if (nameLike) {
        queryTruckOilCardDown({
          word: nameLike
        }).then(rsp => {
          this.oilCardLikeData = rsp.data
        })
      } else {
        this.oilCardLikeData = []
      }
    },
    handleOilCardChangeModal (nameLike = '') { // 加油卡
      queryTruckOilCardDown({
        word: nameLike
      }).then(rsp => {
        this.oilCardLikeDataModal = rsp.data
      })
    },
    viewInvoice (purchaseId) { // 添加发票
      this.visibleInvoice = true
      this.purchaseId = purchaseId
    },
    createInvoice (purchaseId) {
      if (!this.$root._bc.createInvoice) {
        this.$message.error('您无此权限！')
        return
      } // 添加发票
      this.visibleInvoice = true
      this.purchaseId = purchaseId
    },
    handleCancelPurchase () {
      this.visibleInvoice = false
      this.purchaseId = null
      this.handleSubmit()
    }
  },
  mounted () {
    this.$nextTick(() => {
      this.handleSubmit()
    })
  }
}
</script>

<style lang="less" scoped>
.card-container {
  background: #f0f2f5;
  overflow: hidden;
  padding: 24px;
  .ant-tabs-card {
    .ant-tabs-content {
      height: 120px;
      margin-top: -16px;
      .ant-tabs-tabpane {
        background: #fff;
        padding: 40px 24px 24px 24px;
      }
    }
    .ant-tabs-bar {
      border-color: #fff;
      .ant-tabs-tab {
        border-color: transparent;
        background: transparent;
      }
      .ant-tabs-tab-active {
        border-color: #fff;
        background: #fff;
      }
    }
  }
}
.computedData {
  height: 40px;
  line-height: 40px;
  margin-bottom: 24px;
  text-indent: 5px;
}

.descData {
  text-align: right;
  color: #000000d9;
}
</style>
<style>
.ant-card-body1 {
  background: #f9fcff;
  border: 1px #dbe3ff solid;
  padding: 24px 24px 16px 24px;
}
.ant-card-body1 .cgYoul {
  font-size: 40px;
  color: rgba(0, 0, 0, 0.85);
  font-weight: 400;
  margin-bottom: 0;
}
.ant-card-body1 .caiGou {
  margin-bottom: 0;
  line-height: 16px;
}
.ant-card-body1 .cgSale {
  margin-bottom: 0;
  line-height: 16px;
  border-top: 1px #dbe3ff solid;
  padding-top: 16px;
}
.ant-card-body1 .cgSale span {
  float: right;
  font-size: 18px;
  font-weight: bold;
}
</style>
